<?php

namespace app\admin\service\setting;

use think\facade\Cache as CacheStatic;
use think\facade\Env;
use tmcore\base\BaseService;
use tmcore\services\redis\Redis;

class DbRedisService extends BaseService
{
    /**
     * 查看redis信息
     * @param $params
     * @return array
     */
    public static function info($params)
    {
        $redis = (new Redis)->redisObj;

        $info = $redis->info();

        $iterator = null;
        $keys = [];
        $key_list = [];

        $app_debug = Env::get('app_debug', false);
        if($app_debug) {
            // 禁止线上环境使用scan命令,每次扫描100个
            while (false !== ($key = $redis->scan($iterator, config('cache.default.prefix') . '*', 100))) {
                $keys = array_merge($keys, $key);
            }
        }

        if(!empty($params['key'])) $keys = [$params['key']];

        $info_params = [
            'version' => &$info['redis_version'],
            'redis_mode' => ($info['redis_mode'] === 'standalone') ? '单机' : '集群',
            'run_days' => &$info['uptime_in_days'],
            'aof_enabled' => ($info['aof_enabled'] == 0) ? '关闭' : '开启',
            'use_memory' => &$info['used_memory_human'],
            'port' => &$info['tcp_port'],
            'clients' => &$info['connected_clients'],
            'expired_keys' => &$info['expired_keys'],
            'sys_total_keys' => count($keys),
        ];

        $key_names = [
            'version' => 'Redis版本',
            'redis_mode' => '运行模式',
            'run_days' => '运行天数',
            'aof_enabled' => 'AOF状态',
            'port' => '端口',
            'clients' => '客户端连接数',
            'expired_keys' => '已过期key',
            'sys_total_keys' => '已使用key',
        ];

        $data = [];

        foreach ($info_params as $key => $value) {
            if(array_key_exists($key, $key_names)) array_push($data, ['key' => $key, 'desc' => $key_names[$key], 'value' => $value]);
        }

        foreach ($keys as $key => $value) {
            array_unshift($key_list, ['key' => $value]);
        }

        return [
            'keys' => $key_list,
            'server' => $data,
        ];
    }

    /**
     * 查看缓存
     * @param array $params
     * @return mixed
     */
    public static function detail($params)
    {
        $value = CacheStatic::store()->get(self::getKey($params['key']));
        $time = (new Redis)->redisObj->ttl($params['key']);
        return [
            'key' => $params['key'],
            'value' => is_array($value)?json_encode($value, 320):$value,
            'time' => $time > 0?$time:0,
            'len' => strlen($value?json_encode($value, 320):'')
        ];
    }

    /**
     * 编辑缓存
     * @param array $params
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function edit($params)
    {
        return CacheStatic::store()->set(self::getKey($params['key']), $params['value'], isset($params['time'])?$params['time']:0);
    }

    /**
     * 删除缓存
     * @param array $params
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function delete($params)
    {
        return CacheStatic::store()->delete(self::getKey($params['key']));
    }


    /**
     * 去除key前缀
     * @param $key
     * @return false|string
     */
    private static function getKey($key) {
        $prefix = env('redis.prefix', '');
        if(strpos($key, $prefix) !== false) {
            return substr($key, strlen($prefix));
        } else {
            return $key;
        }
    }
}